package com.bckj.fastboot.mq.ons.retry;

import com.aliyun.openservices.ons.api.Consumer;
import com.aliyun.openservices.ons.api.ONSFactory;
import com.aliyun.openservices.ons.api.Producer;
import com.bckj.fastboot.core.extra.retry.RetryProducer;
import com.bckj.fastboot.mq.ons.FastOnsAutoConfiguration;
import com.bckj.fastboot.mq.ons.OnsProperties;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Properties;

@Configuration
@ConditionalOnProperty(
        prefix = "fastboot.ons.config",
        name = {"retryTopic", "retryGroup"}
)
@AutoConfigureAfter(FastOnsAutoConfiguration.class)
public class FastRetryConfiguration {

    @Value("${fastboot.ons.config.retryTopic}")
    private String retryTopic;
    @Value("${fastboot.ons.config.retryGroup}")
    private String retryGroupId;

    @Bean
    public RetryProducer retryProducer(Producer producer) {
        return new OnsRetryProducer(producer);
    }

    @Bean
    public Consumer retryConsumer(OnsProperties properties, RetryProducer retryProducer) {
        Properties config = new Properties();
        config.putAll(properties.getConfig());
        config.setProperty("GROUP_ID", retryGroupId);
        Consumer consumer = ONSFactory.createConsumer(config);
        consumer.subscribe(retryTopic, "*", new OnsRetryConsumer(retryProducer));
        consumer.start();
        return consumer;
    }
}
